﻿using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Business;
using Model;
using Newtonsoft.Json;
using SignalR通讯.Tool;

namespace SignalR通讯.Controllers
{
    public class LogoController : Controller
    {
        public static List<User> OnlineUsers = new List<User>(); // 在线用户列表
        public ActionResult LogoView()
        {
            return View();
        }

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="userNmae">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public JsonResult Login(string userNmae, string password)
        {
            OperateStatus operateStatus = new OperateStatus();
            var model = new User
            {
                UserName = userNmae,
                Password = password
            };
            UserDataBase list = new UserDataBase();
            var user =list.SelectUserName(model);
            if (!user)
            {
                operateStatus.Message = "用户名不存在";
                return Json(operateStatus);
            }
            var pwd = list.SelectPassword(model);
            if (!pwd)
            {
                operateStatus.Message = "密码不正确";
                return Json(operateStatus);
            }

            var userInfo =list.GetSelectUserName(model);

            var modelInfo = new User
            {
                UserName = userNmae,
                Password = password,
                ConnectionId = userInfo.ConnectionId,
                UserId = userInfo.UserId
            };
            modelInfo.UserName = HttpUtility.UrlEncode(userNmae);

            //添加list用于下拉框
            OnlineUsers.Add(new User
            {
                ConnectionId = modelInfo.ConnectionId,
                UserId = modelInfo.UserId,
                UserName = modelInfo.UserName
            });
            // 写入cookie
            CookieConfig.SetCookie("user", modelInfo);
            operateStatus.Message = "登录成功";
            operateStatus.ResultSign = ResultSign.Successful;

            #region 写入cookies 私聊用

            var context = HttpContext;
            //帐户信息写入Cookie,自行加密
            context.Response.Cookies.Add(new HttpCookie("user1") { Value = JsonConvert.SerializeObject(OnlineUsers) });
            //唯一的登陆ID,作为连接ID
            context.Response.Cookies.Add(new HttpCookie("user2") { Value = modelInfo.UserId });

            #endregion
            return Json(operateStatus);
        }
	}
}